package com.g2room.myuall.grap.univ;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import com.g2room.driving.grap.article.to.ImgTo;
import com.g2room.driving.util.Constants;
import com.g2room.driving.util.ImageUtil;
import com.g2room.myuall.grap.univ.po.ImgPo;
import com.g2room.myuall.util.DbUtil;

public class HandleImages implements Runnable {
	static String localImgDir = Constants.localImgDir;
	public static List<ImgTo> imgTos = new ArrayList<ImgTo>();
	public static List<String> list= getImages();
//	public static Map<String, Boolean> itMap = getImagesFromFile();
	
	static {
		list.add("http://img1.gtimg.com/7/733/73372/7337224_1200x1000_343.jpg");
		list.add("http://img1.gtimg.com/7/733/73372/7337221_1200x1000_343.jpg");
		list.add("http://img1.gtimg.com/7/733/73372/7337223_1200x1000_343.jpg");
		list.add("http://img1.gtimg.com/7/733/73372/7337226_1200x1000_343.jpg");
		list.add("http://img1.gtimg.com/7/733/73372/7337225_1200x1000_343.jpg");
		list.add("http://img1.gtimg.com/7/733/73372/7337222_1200x1000_343.jpg");



	}
	
	/**
	 * 获取指定位数的数字
	 * 
	 * @param len 指定长度
	 * @return
	 */
	public static String genRandomNum(int len) {
		//35是因为数组是从0开始的，26个字母+10个数字
		final int maxNum = 36;
		int i; //生成的随机数
		int count = 0; //生成的密码的长度
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < len) {
			//生成随机数，取绝对值，防止生成负数，
			i = Math.abs(r.nextInt(maxNum)); //生成的数最大为36-1
			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}
	public static int genRandomNum() {
		//35是因为数组是从0开始的，26个字母+10个数字
		final int maxNum = 12;
		int i = 0; //生成的随机数
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (i  < 5) {
			//生成随机数，取绝对值，防止生成负数，
			i = Math.abs(r.nextInt(maxNum)); //生成的数最大为36-1
		}
		return i;
	}
	public static void main(String[] args) {
		
//		File file = new File("D:/userdata/imags/cq/jp");
//		String path = "D:/userdata/imags/cq/online/";
//		int j = 0;
//		int i = 0;
//		int num = 0;
//		for(File f : file.listFiles()) {
//			try {
//				Thread.sleep(12);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//			
//			if(j == 0 || j >= num) {
//				j = 0;
//				i = Integer.valueOf(genRandomNum(6));
//				num = Integer.valueOf(genRandomNum());
//				File file01 = new File(path + i + "/");
//				if(!file01.exists()) {
//					file01.mkdir();
//				}
//			}
//			j++;
//			
//			File dest = new File(path + i + "/" + System.currentTimeMillis() + ".jpg");
//			f.renameTo(dest);
//		}
//		String dir = "11010";
//		File file = new File("D:/userdata/imags/cq/jp/" + dir);
//		for(File f : file.listFiles()) {
////			if(f.isDirectory()) {
////				for(File fi : f.listFiles()) {
////					String fn = fi.getPath().substring(fi.getPath().indexOf("online") + 7).replace("\\", "/");
//					System.out.println("insert into life_beauty_img (img_url, album) "
//							+ "values ('http://img.023sh.cn/imgs/mv/"+ dir + "/"+f.getName()+"', 28);");
////				}
////			}
//		}
		
		grapImgs(list);
		
		
////		GrapZdx zdx = new GrapZdx();
////		System.out.println(its.size() + "==" + itMap.size());
////		grapImgs(its);
//		
//		// 以下为抓取
//		for(int i =0; i<11; i++) {
//			try {
//				Thread.sleep(10);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//			HandleImages gue = new HandleImages();
//			Thread t = new Thread(gue);
//			t.start();
//		}
	}
	


	@Override
	public void run() {
		List<String> imgPos = getUrl();
		if(null == imgPos) return;
		grapImgs(imgPos);
	}
	
	public static AtomicInteger page = new AtomicInteger(0);
	private static synchronized List<String> getUrl() {
		if(page.intValue() > list.size()) return null;
		List<String> ips = list.subList(page.intValue(), Math.min(list.size(), page.intValue() + 1211));
		page.addAndGet(290);
		return ips;
	}
	
	public static void grapImgs(List<String> its) {
		GrapZdx zdx = new GrapZdx();
		for(String imgUrl : its) {
			System.out.println(imgUrl);
			String iu = imgUrl.replace("jpg.thumb.jpg/0", "jpg");
			String fn = iu.substring(iu.lastIndexOf("/") + 1);

//			// 存在则不抓取
//			if(itMap.containsKey(fn)) {
//				continue;
//			}
			try {
				ImageUtil.downloadImage(imgUrl, localImgDir, "jp/p2", fn);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(imgUrl);
				zdx.insert2ErrDb(imgUrl, 0);
			}
//			String smallUrl = img.getUrl().replace(".jpeg", "_190.jpeg").replace(".gif", "_190.gif").replace(".png", "_190.png").replace(".jpg", "_190.jpg");
//			String smallFn = smallUrl.substring(smallUrl.lastIndexOf("/") + 1);
//			try {
//				ImageUtil.downloadImage(smallUrl, localImgDir, "myuall/small", smallFn);
//			} catch (Exception e) {
//				e.printStackTrace();
//				zdx.insert2ErrDb(smallUrl, 1);
//			}
		}
	}
	
	public static void updateImg() {
//		List<ImgPo> its = getImages();
//		for(ImgPo img : its) {
//			updateImg(img);
//		}
	}
	
	public static void getImgs(String dir) {
//		getImageSrc();
		Integer[] sids = new Integer[]{};
		
		StringBuffer errSrcSb = new StringBuffer();
		for(Integer in : sids) {
			String url = "http://gkcx.eol.cn/upload/schoollogo/"+in+".jpg";
			if(null == in) {
				continue;
			}
			try {
				ImageUtil.downloadImage(url, localImgDir, dir + "/badge", "badge"+in+".jpg");
//				insertImg(it, filePath);
			} catch (Exception e) {
//				System.out.println(it.getGrapSrc() + "\n");
				e.printStackTrace();
			}
		}
//		DbUtil.closeConn();
//		// 生成update语句
//		System.out.println(errSrcSb.toString());
	}
	
	/**
	 * 获取所有的图片地址
	 */
	public static void getImageSrc() {
		try {
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
			String sql = "select id,photo,images from tog_univ where photo like '%http://%' or images like '%http://%' ";
			ResultSet rs = statement.executeQuery(sql);
			while(rs.next()) {
				String p = rs.getString("photo");
				int id = rs.getInt("id");
				if(null != p && p.trim().length()>5) {
					ImgTo it = new  ImgTo();
					it.setId(id);
					it.setType(1);
					it.setGrapSrc(p);
					imgTos.add(it);
				}

				String img = rs.getString("images");
				if(null != img && img.trim().length()>5) {
					String[] imgs = img.split(",");
					for(String i : imgs) {
						ImgTo it = new  ImgTo();
						it.setId(id);
						it.setType(0);
						it.setGrapSrc(i);
						imgTos.add(it);
					}
				}
			}
			rs.close();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param oldSrc
	 * @param grapSrc
	 * @param localSrc
	 * @param type
	 */
	public static void insertImg(ImgTo it, String localSrc) {
		try {
			Connection connection = DbUtil.getConn();
			PreparedStatement statement = connection.prepareStatement("insert into tog_images(grapSrc, localSrc, type, artiId) values(?, ?, ?, ?)");
			statement.setString(1, it.getGrapSrc());
			statement.setString(2, localSrc);
			statement.setInt(3, it.getType());
			statement.setInt(4, it.getId());
			statement.execute();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	

	
	/**
	 * 从图片表获取所有图片信息
	 */
	public static List<String> getImages() {
		List<String> its = new ArrayList<String>();
//		try {
//			Connection connection = DbUtil.getConn();
//			Statement statement = connection.createStatement();
//			String sql = "select badge from univ_info_ext1_y";
//			ResultSet rs = statement.executeQuery(sql);
//			while(rs.next()) {
//				its.add(rs.getString("badge"));
//			}
//			rs.close();
//			statement.close();
//		} catch(Exception e) {
//			e.printStackTrace();
//		}
		return its;
	}
	
	public static Map<String, Boolean> getImagesFromFile() {
		Map<String, Boolean> imgs = new HashMap<String, Boolean>();
		File f = new File("E:/高绪国/资料/images/20160804/myuall/img");
		String[] fns = f.list();
		for(String fn : fns) {
			imgs.put(fn, true);
		}
		return imgs;
	}
	/**
	 * 
	 * @param oldSrc
	 * @param grapSrc
	 * @param localSrc
	 * @param type
	 */
	public static void updateImg(ImgTo it) {
		try {
			Connection connection = DbUtil.getConn();
			PreparedStatement statement = connection.prepareStatement("update tog_univ set images=replace(images, ?, ?) where id=?");
			statement.setString(1, it.getGrapSrc());
			statement.setString(2, it.getOldSrc());
			statement.setInt(3, it.getId());
			statement.execute();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
